<template>
  <div class="app-container-custom">
    <el-row :gutter="10">
      <el-col :span="5" :xs="24">
        <el-card shadow="never">
          <org-tree ref="orgTree" modelType="'dept','community','floor','unit','room'" @nodeClick="handleNodeClick" @firstNodeClick="handleNodeClick"/>
        </el-card>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-card shadow="never">
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="代码" prop="rometerCode">
              <el-input
                v-model="queryParams.rometerCode"
                placeholder="请输入代码"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="仪表种类" prop="kindId">
              <el-select v-model="queryParams.kindId" placeholder="请选择仪表种类" clearable>
                <el-option v-for="item in kindOptions"
                  :key="item.kindId"
                  :label="item.kindName"
                  :value="item.kindId"/>
              </el-select>
            </el-form-item>
            <el-form-item label="仪表箱" prop="boxId">
              <el-select v-model="queryParams.boxId" placeholder="请选择仪表箱" clearable>
                <el-option v-for="item in boxOptions"
                  :key="item.boxId"
                  :label="item.boxName"
                  :value="item.boxId"/>
              </el-select>
            </el-form-item>
            <el-form-item label="表号" prop="tableNumber">
              <el-input
                v-model="queryParams.tableNumber"
                placeholder="请输入表号"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['payfee:meter:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['payfee:meter:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['payfee:meter:remove']"
              >删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
            :loading="exportLoading"
                @click="handleExport"
                v-hasPermi="['payfee:meter:export']"
              >导出</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                icon="el-icon-printer"
                size="mini"
                :disabled="multiple"
                @click="createQecode"
              >二维码</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table v-loading="loading" :data="meterList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="代码" align="center" prop="rometerCode" />
            <el-table-column label="仪表种类" align="center" prop="kindName"  width="80"/>
            <el-table-column label="所属房间" align="center" prop="roomName"  width="180" show-overflow-tooltip/>
            <el-table-column label="所属机构" align="center" prop="deptName"  width="180"/>
            <el-table-column label="倍率" align="center" prop="rateDischar"  width="60"/>
            <el-table-column label="回程" align="center" prop="ticket" width="120"/>
            <el-table-column label="损耗率" align="center" prop="wastage" />
            <el-table-column label="上次读取时间" align="center" prop="lastTime"  width="120">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.lastTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="上次读数" align="center" prop="lastReading" />
            <el-table-column label="系数" align="center" prop="coefficient" />
            <el-table-column label="仪表箱" align="center" prop="boxName" width="100"/>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-col>
    </el-row>
    <!-- 添加或修改房间仪表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body class="form-class">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="8" :xs="24">
              <el-form-item label="代码" prop="rometerCode">
                <el-input v-model="form.rometerCode" placeholder="请输入代码" />
              </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
              <el-form-item label="仪表种类" prop="kindId">
                <el-select v-model="form.kindId" placeholder="请选择仪表种类" clearable>
                  <el-option v-for="item in kindOptions"
                    :key="item.kindId"
                    :label="item.kindName"
                    :value="item.kindId"/>
                </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
              <el-form-item label="所属房间" prop="roomId" >
                <el-input v-model="form.roomName"  placeholder="请选择对应房间" readonly >
                  <el-button slot="append" icon="el-icon-search"  @click="()=>this.$refs.roomRef.show()" ></el-button>
                </el-input>
              </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
              <el-form-item label="倍率" prop="rateDischar">
                <el-input-number v-model="form.rateDischar" :precision="4" :step="0.1" :min="0" style="width: 100%"></el-input-number>
              </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
              <el-form-item label="回程" prop="ticket">
                <el-input-number v-model="form.ticket" :precision="4" :step="0.1" :min="0" style="width: 100%"></el-input-number>
              </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
              <el-form-item label="损耗率" prop="wastage">
                <el-input-number v-model="form.wastage" :precision="4" :step="0.1" :min="0" style="width: 100%"></el-input-number>
              </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
              <el-form-item label="上次读取时间" prop="lastTime">
                <el-date-picker clearable size="small"
                  v-model="form.lastTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择上次读取时间">
                </el-date-picker>
              </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
              <el-form-item label="上次读数" prop="lastReading">
                <el-input-number v-model="form.lastReading" :precision="4" :step="0.1" :min="0" style="width: 100%"></el-input-number>
              </el-form-item>
          </el-col>
      <!--    <el-col :span="8" :xs="24">
              <el-form-item label="总表" prop="totals">
                <el-input v-model="form.totals" placeholder="请输入总表" />
              </el-form-item>
          </el-col>-->
          <el-col :span="8" :xs="24">
              <el-form-item label="仪表地址" prop="meterAddress">
                <el-input v-model="form.meterAddress" placeholder="请输入仪表地址" />
              </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
              <el-form-item label="系数" prop="coefficient">
                <el-input-number v-model="form.coefficient" :precision="4" :step="0.1" :min="0" style="width: 100%"></el-input-number>
              </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
              <el-form-item label="仪表箱" prop="boxId">
                <el-select v-model="form.boxId" placeholder="请选择仪表箱" clearable>
                  <el-option v-for="item in boxOptions"
                    :key="item.boxId"
                    :label="item.boxName"
                    :value="item.boxId"/>
                </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
              <el-form-item label="表号" prop="tableNumber">
                <el-input v-model="form.tableNumber" placeholder="请输入表号" />
              </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
              <el-form-item label="短编码" prop="shortCode">
                <el-input v-model="form.shortCode" placeholder="请输入短编码" />
              </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
              <el-form-item label="出厂铭牌" prop="nameplate">
                <el-input v-model="form.nameplate" placeholder="请输入出厂铭牌" />
              </el-form-item>
          </el-col>
          <el-col :span="16" :xs="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark"  type="textarea"  placeholder="请输入备注" />
              </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <TableSelect
      ref="roomRef"
      :listColumns="roomColumns"
      gridUrl="/property/room/list"
      @rowClick="roomSelect"
      dialogWidth="780px"
      :defaultParam="{nodeId: this.queryParams.nodeId}"
      title="房屋字典"/>

    <el-dialog
      :visible.sync="codeOpen"
      width="960px"
      title="二维码"
    >
      <div id="printDiv" v-if="codeOpen">
        <el-form ref="form" label-width="0px" size="small">
          <el-row>
            <el-col :span="4" v-for="item in selections">
              <el-form-item label=""  >
                <div :id="item.rometerId">{{item.rometerCode}}</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-print="'#printDiv'">打印</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMeter, getMeter, delMeter, addMeter, updateMeter, exportMeter } from "@/api/payfee/meter";
import { listKind} from "@/api/payfee/kind";
import { listBox} from "@/api/payfee/box";
// import QRCode from 'qrcodejs2'
export default {
  name: "Meter",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      codeOpen:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房间仪表表格数据
      meterList: [],
      kindOptions:[],
      boxOptions:[],
      selections:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rometerCode: null,
        kindId: null,
        roomId: null,
        boxId: null,
        tableNumber: null,
        nodeId:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        boxId: [
          { required: true, message: "仪表箱不能为空", trigger: "blur" }
        ],
        rometerCode: [
          { required: true, message: "代码不能为空", trigger: "blur" }
        ],
        kindId: [
          { required: true, message: "仪表种类不能为空", trigger: "blur" }
        ],
        roomId: [
          { required: true, message: "所属房间不能为空", trigger: "blur" }
        ],
        lastTime: [
          { required: true, message: "上次读取时间不能为空", trigger: "blur" }
        ],
        lastReading: [
          { required: true, message: "上次读数不能为空", trigger: "blur" }
        ],
      },
      roomColumns:[
        {title:'楼栋',key:'floorName',type:'',isSearch:true},
        {title:'单元',key:'unitName',type:'',isSearch:true},
        {title:'房屋编号',key:'roomNum',type:'',isSearch:true},
        {title:'客户姓名',key:'customName',type:'',isSearch:true},
      ],
      currentNode:null
    };
  },
  created() {
    //this.getList();
    this.getKindList();
    this.getBoxList();
  },
  watch:{
    'form.communityId'(v){
      listBox({'nodeId':this.form.communityId}).then(response => {
        this.boxOptions = response.rows;
      })
    }
  },
  methods: {
    /** 查询房间仪表列表 */
    getList() {
      this.loading = true;
      listMeter(this.queryParams).then(response => {
        this.meterList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getKindList(){
      listKind().then(response => {
        this.kindOptions = response.rows;
      })
    },
    getBoxList(){
      listBox().then(response => {
        this.boxOptions = response.rows;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        rometerId: null,
        rometerCode: null,
        kindId: null,
        roomId: null,
        deptId: null,
        rateDischar: null,
        ticket: null,
        wastage: null,
        lastTime: null,
        lastReading: null,
        totals: null,
        meterAddress: null,
        coefficient: null,
        boxId: null,
        tableNumber: null,
        shortCode: null,
        nameplate: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        roomName:null,
        communityId:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selections = selection;
      this.ids = selection.map(item => item.rometerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if(this.currentNode && this.currentNode.modelType=='room'){
        this.form.roomId = this.currentNode.id
        this.form.roomName = this.currentNode.label
      }else{
        this.form.roomId = null
        this.form.roomName = null
      }
      this.open = true;
      this.title = "添加房间仪表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const rometerId = row.rometerId || this.ids
      getMeter(rometerId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改房间仪表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.rometerId != null) {
            updateMeter(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            listMeter({'roomId':this.form.roomId,'kindId':this.form.kindId}).then(response => {
              if (response.total !=0){
                this.msgSuccess("一个房间只能绑定一个主表,不能绑定!");
                return false;
              }else {
                addMeter(this.form).then(response => {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const rometerIds = row.rometerId || this.ids;
      this.$confirm('是否确认删除房间仪表编号为"' + rometerIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delMeter(rometerIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有房间仪表数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportMeter(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    roomSelect(index,row){
      this.form.roomName= row.roomName;
      this.form.roomId=row.id;
      this.form.communityId = row.communityId
    },
    createQecode(){
      this.codeOpen=true
      this.$nextTick(function(){
        for(let i in this.selections){
          let qrcode = new QRCode(this.selections[i].rometerId, {
            width: 100,
            height: 100, // 高度
            text:"/copyroom/index?id="+this.selections[i].rometerId,
            // text: this.selections[i].nurseryId+"-"+ this.selections[i].coder,// 二维码内容
            // render: 'canvas' // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
            // background: '#f0f'
            // foreground: '#ff0'
          })
          console.log(qrcode)
        }
      });

    },
    handleNodeClick(node){
      this.currentNode = node;
      this.queryParams.nodeId = node.id
      this.getList()
    }
  }
};
</script>
<style lang="scss" scoped>
  .form-class{
    .el-row{
      display:flex;
      flex-wrap: wrap;
    }
  }

</style>
